#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

void blackscreen(Mat &image)
{
    int a, b, sum;
    a = image.rows;
    b = image.cols;
    sum = a * b;
    //cout << sum << endl;
    int c = 0;
    //双重循环，遍历所有的像素值
    for (int i = 0; i < a; i++) //行循环
    {
        uchar *data = image.ptr<uchar>(i); //获取第i行的首地址
        for (int j = 0; j < b; j++)        //列循环
        {
            //cout << (int)data[j] << endl;
            if ((int)data[j] < 30)
            {
                c++;
            }
        }
    }
    static int framenum = 0;
    //cout << c << endl;
    double Rate = (double)c / sum;
    //cout << Rate << endl;
    if (Rate > 40 && Rate < 80)
    {
        framenum++;
        printf("遮挡\n");
    }
    cout << framenum << endl;
    //double frozen = (double)framenum / totalFrameNumber;
    //if (frozen > 0.9)
    //   printf("冻结\n");
}

int main() //occlude
{
    //读入视频
    VideoCapture capture("/Users/lukeskywalker/Desktop/occlude.mov");
    //VideoCapture capture(0);
    //namedWindow("camera", WINDOW_AUTOSIZE);
    //namedWindow("moving area", WINDOW_AUTOSIZE);
    //获取整个帧数

    Mat frame;
    Mat gray;
    Mat tempframe;
    int framenum = 0;
    //读取一帧处理
    while (true)
    {
        if (!capture.isOpened())
        {
            cout << "read video failure" << endl;
            return -1;
        }
        //tempframe = capture.read(frame);

        //获取整个帧数
        long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
        //cout << "整个视频共" << totalFrameNumber << "帧" << endl;

        capture >> frame;
        tempframe = frame;
        framenum++;
        if (framenum == 1)
        {
            cvtColor(tempframe, gray, CV_BGR2GRAY);
        }
        if (framenum >= 2)
        {
            cvtColor(tempframe, gray, CV_BGR2GRAY); //转化为单通道灰度图，此时currentFrame已经存了tempFrame的内容

            //显示图像
            imshow("camera", tempframe);
            imshow("moving area", gray);
        }

        if (!(framenum % 1))
        {
            printf("f:%d\n", framenum);
            //***suanfa;
        }

        blackscreen(gray);
        //把当前帧保存作为下一次处理的前一帧
        waitKey(33);
    } //end while
}